const Admin = require("../models/Admin");
const { hash, compare } = require("../utils/hash");

//添加管理员用户
const addAdmin = async ({ username, password }) => {
  //查找是否有相同用户名的用户
  let result = await findAdminByUsername(username);
  if (result.msg === "查找成功") {
    return {
      msg: "该用户已经注册了 请更换用户名",
      status: 0,
    };
  } else {
    let result = await Admin.create({
      username,
      password,
    });
    return {
      msg: "注册成功",
      status: 1,
      data: result.toJSON(),
    };
  }
};
//根据用户名查找用户
const findAdminByUsername = async (username) => {
  let result = await Admin.findOne({
    where: {
      username,
    },
  });
  if (result) {
    return {
      msg: "查找成功",
      data: result,
    };
  } else {
    return {
      msg: "查找失败",
    };
  }
};
//根据用户名和密码查找用户
const findAdmin = async ({ username, password }) => {
  //将password和数据库中的密码进行比较
  let result = await findAdminByUsername(username);
  if (result.msg === "查找失败") {
    return {
      msg: "用户不存在",
      status: 0,
    };
  } else {
    let admin = result.data;
    let { username: dbUsername, password: dbPassword, id } = admin;
    if (dbUsername === username && compare(password, dbPassword)) {
      return {
        msg: "登录成功",
        status: 1,
        id
      };
    } else {
      return {
        msg: "密码错误",
        status: 0,
      };
    }
  }
};
module.exports = {
  addAdmin,
  findAdmin,
};
